package com.allprs.web.controller.common;

import com.allprs.common.config.ProjectConfig;
import com.allprs.common.core.domain.AjaxResult;
import com.allprs.common.utils.StringUtils;
import com.allprs.common.utils.file.FileUploadUtils;
import com.allprs.common.utils.file.FileUtils;
import com.allprs.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用请求处理
 *
 * @author wjf
 */
@RestController
@Slf4j
@Api(tags = "通用请求")
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private ServerConfig serverConfig;


    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = ProjectConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", file.getOriginalFilename());
            ajax.put("fileId",fileName);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用下载请求
     *
     * @param fileId 文件名称
     * @param relaName   是否删除
     */
    @GetMapping("/download")
    @ApiOperation(value = "文件下载")
    public void fileDownload(String fileId, String relaName, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileId)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileId));
            }
            String filePath = ProjectConfig.getUploadPath() + fileId.substring(15);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, relaName);
            FileUtils.writeBytes(filePath, response.getOutputStream());

        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}
